<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请发布您的评论"
      show-word-limit
    />
    <van-button class="post-btn" @click="onPost" :disabled="!message.length"
      >发布</van-button
    >
  </div>
</template>

<script>
import { addComment } from "@/api/comment";
export default {
  name: "CommentPost",
  components: {},
  // 接收祖先组件的数据
  // inject: {
  //   articleId: {
  //     type: [Number, String, Object],
  //     default: null,
  //   },
  // },
  props: {
    target: {
      type: [Number, String, Object],
      required: true,
    },
  },
  data() {
    return {
      message: "",
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    //   发布评论
    async onPost() {
      this.$toast.loading({
        message: "发布中...",
        forbidClick: true, //禁用背景点击
        duration: 0, //持续时间，默认2000 0表示持续展示不关闭
      });
      try {
        const { data } = await addComment({
          target: this.target.toSrting(), //评论的目标id（评论文章即为文章id，对评论进行回复则为评论id）
          content: this.message, //评论内容
          art_id: null, //	文章id，对评论内容发表回复时，需要传递此参数，表明所属文章id。对文章进行评论，不要传此参数。
        });
        // 清空文本域
        this.message = "";
        // 向父组件传递
        this.$emit("post-success", data.data.new_obj);
        // 成功提示
        this.$toast.success("发布成功");
      } catch (err) {
        //   错误提示信息
        let errmessage = "";
        if (err.response && err.response.status) {
          switch (err.response.status) {
            case 401:
              errmessage = "用户未认证";
              break;
            case 403:
              errmessage = "文章已关闭评论";
              break;
            case 507:
              errmessage = "数据库异常";
              break;
          }
        }
        this.$toast.fail(errmessage);
      }
    },
  },
};
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
